package cn.com.client.reference;

import cn.com.cluster.Cluster;
import cn.com.cluster.FailOverCluster;
import cn.com.cluster.ServiceDictionary;
import cn.com.common.Constant;
import cn.com.common.RegistryInfo;
import cn.com.common.URI;
import cn.com.registry.EtcdRegistryServiceFactory;
import cn.com.registry.RegistryFactory;
import cn.com.registry.RegistryService;
import cn.com.rpc.invoke.Invoker;

/**
 * @author jiaming
 */
public class ZhurongReference implements Reference {

    private RegistryFactory registryFactory = new EtcdRegistryServiceFactory();
    private Cluster cluster = new FailOverCluster();

    @Override
    public <T> Invoker<T> refer(RegistryInfo registryInfo, URI uri) {
        ServiceDictionary dictionary = new ServiceDictionary();
        String address = registryInfo.getHost() + ":" + registryInfo.getPort();
        RegistryService nameService = registryFactory.getRegistry(address);
        nameService.onListener(dictionary);
        return doRefer(cluster, nameService, dictionary, uri);
    }

    private <T> Invoker<T> doRefer(Cluster cluster, RegistryService nameService,
                                   ServiceDictionary serviceDictionary, URI uri) {
        Invoker invoker = cluster.add(serviceDictionary);
        RegistryInfo registryInfo = new RegistryInfo();
        registryInfo.setHost(uri.getHost());
        registryInfo.setPort(uri.getPort());
        registryInfo.setRoot(Constant.APPLICATION_PATH);
        registryInfo.setAppName(uri.getServiceName());
        nameService.subscribe(registryInfo,Constant.SERVER_PATH);
        return invoker;
    }

}
